package com.pirestupppai.imagetool.mattingtool;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.pirestupppai.common.Constant;
import com.pirestupppai.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 手指拖动区域抠图
 */

public class MattingView extends View {
    /**
     *  贴纸图层，在测量时，设置缩放matrix
     */
    private Context mContext;
    public Bitmap mBgBitmap, mFgBitmap;
    private Canvas mCanvas;
    private List<CustomPath> mPathList = new ArrayList<>();      // 用于保存抠图或者橡皮擦绘制的路径
    private CustomPath curCustomPath;        // 当前path
    private Canvas mTransParentCanvas;       // 绘制背景透明色

    private boolean mIsMatting = true;       // 当前抠图或者橡皮擦的状态
    private Matrix mBackgroundMatrix;
    private int surplusHeight;              // 当前屏幕剩余高度
    private float scaleRate;                // 图片缩放比例

    public MattingView(Context context) {
        super(context);
        mContext = context;
    }

    public MattingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
    }

    // 根据传入的图层Id初始化
    public void setBackgroundBitmap(Bitmap  bitmap) {

        surplusHeight = Constant.HEIGHT_OF_SCREEN - Constant.HEIGHT_OF_STATUSBAR
                - Utils.dpToPx(mContext, 64) - Utils.dpToPx(mContext, 85);

        mBgBitmap = bitmap;
        mFgBitmap = Bitmap.createBitmap(mBgBitmap.getWidth(), mBgBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mFgBitmap);
        mCanvas.drawColor(Color.parseColor("#00000000"));
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        requestLayout();
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // draw背景为白色
        canvas.drawColor(Color.parseColor("#FFFFFF"));

        for (int i = 0; i < mPathList.size(); i++) {
            mCanvas.drawPath(mPathList.get(i).mPath, mPathList.get(i).mPaint);
        }

        canvas.drawBitmap(mBgBitmap, mBackgroundMatrix, null);
        canvas.drawBitmap(mFgBitmap, mBackgroundMatrix, null);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        mBackgroundMatrix = new Matrix();    // 整个绘制过程会多次测量，所以需要在这里初始化
        if (mBgBitmap != null) {
            float surplusRate = (float) Constant.WIDTH_OF_SCREEN / (float) surplusHeight;
            float pictureRate = (float) mBgBitmap.getWidth() / (float) mBgBitmap.getHeight();
            if (pictureRate > surplusRate) {
                scaleRate = (float) Constant.WIDTH_OF_SCREEN / (float) mBgBitmap.getWidth();
                setMeasuredDimension(Constant.WIDTH_OF_SCREEN, Constant.WIDTH_OF_SCREEN * mBgBitmap.getHeight() / mBgBitmap.getWidth());
            } else {
                scaleRate = (float) surplusHeight / (float) mBgBitmap.getHeight();
                setMeasuredDimension(surplusHeight * mBgBitmap.getWidth() / mBgBitmap.getHeight(), surplusHeight);
            }
            // 设置贴纸图层的缩放matrix
            mBackgroundMatrix.postScale(scaleRate, scaleRate);
        } else {
            setMeasuredDimension(Constant.WIDTH_OF_SCREEN, surplusHeight);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // 手指滑动的区域是放大或缩小后的图片，考虑缩放比例
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                curCustomPath = new CustomPath();
                mPathList.add(curCustomPath);
                if (mIsMatting) {
                    curCustomPath.setmPaintColor(Color.parseColor("#4F000000"));
                } else {
                    curCustomPath.setmPaintColor(Color.parseColor("#00000000"));
                }
                curCustomPath.mPath.moveTo(event.getX() / scaleRate, event.getY() / scaleRate);
                break;
            case MotionEvent.ACTION_MOVE:
                curCustomPath.mPath.lineTo(event.getX() / scaleRate, event.getY() / scaleRate);
                break;
        }
        invalidate();
        return true;
    }

    /**
     *  获取抠图的bitmap
     */
    public Bitmap getBgBitmap() {

        int originFgWidth = mFgBitmap.getWidth();
        int originFgHeidht = mFgBitmap.getHeight();

        int rectLeft = originFgWidth;    // 根据前景色的选中部分，获得抠图区域的矩形边界
        int rectRight = 0;
        int rectTop = originFgHeidht;
        int rectBottom = 0;

        Bitmap mTransBitmap = Bitmap.createBitmap(originFgWidth, originFgHeidht, Bitmap.Config.ARGB_8888);
        mTransParentCanvas = new Canvas(mTransBitmap);
        mTransParentCanvas.drawColor(Color.parseColor("#00000000"));
        mTransParentCanvas.drawBitmap(mBgBitmap, 0, 0, null);

        boolean hasChoice = false;      // 是否选择抠图区域

        for (int i = (originFgWidth - 1); i >= 0; i--) {
            for (int j = 0; j < originFgHeidht; j++) {
                if (mFgBitmap.getPixel(i, j) == Color.parseColor("#4F000000")) {
                    if (rectLeft > i) {
                        rectLeft = i;
                    }

                    if (rectRight < i) {
                        rectRight = i;
                    }

                    if (rectTop > j) {
                        rectTop = j;
                    }

                    if (rectBottom < j) {
                        rectBottom = j;
                    }

                    hasChoice = true;

                } else {
                    mTransBitmap.setPixel(i, j, Color.TRANSPARENT);
                }
            }
        }
        if (hasChoice) {
            // 根据抠图的边界裁剪图片
            Bitmap cutBgBitmap = Bitmap.createBitmap (mTransBitmap, rectLeft, rectTop, (rectRight - rectLeft), (rectBottom - rectTop));
            return cutBgBitmap;
        } else {
            return mBgBitmap;
        }
    }

    /**
     *  设置当前为抠图或者橡皮擦
     */
    public void SetMattingStatus(boolean isMatting) {
        this.mIsMatting = isMatting;
    }
}